package day14;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.Socket;
import java.util.Scanner;

public class Client2 {
    static volatile boolean isEsc;//默认为false 没有退出
    public static void main(String[] args) throws IOException {
        Socket client = new Socket("192.168.9.11", 9999);
        OutputStream os = client.getOutputStream(); //写入
        Scanner sc = new Scanner(System.in);
        //缺少一个像服务端 读取数据 由于上面的读写和监听服务端的数据
        //是相互独立的，所以他也是一个线程来实现的
        new ClientThread2(client).start();
        System.out.println("请输入你的姓名");
        String name = sc.nextLine();
        while (true) {
            System.out.println("请输入你要说的内容：esc退出聊天室");
            String msg = sc.nextLine();
            if (msg != null) {
                if (msg.contains("esc")) {
                    os.write((name + "说：退出聊天室esc\n").getBytes());
                    isEsc =true; //标记已经退出
                    break;
                } else {
                    os.write((name + "说：" + msg + "\n").getBytes());
                }
            }
        }
        os.close();
        client.close();
    }
}
class ClientThread2 extends Thread{
    Socket client;
    public ClientThread2(Socket client){
        this.client=client;
    }

    @Override
    public void run() {
        try {
            BufferedReader br = new BufferedReader(new InputStreamReader(client.getInputStream()));
            while (!Client2.isEsc){
                String msg = br.readLine();
                if (msg!=null) System.out.println(msg);
            }
        } catch (Exception e) {

        }
    }
}